/*
 * SquibMediaPane.scala
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package tfd.scala.squib.jmc

import java.awt.{Dimension, Rectangle}
import java.net.{URI}
import javax.swing.{JComponent}

import com.sun.media.jmc.{JMediaPane, MediaProvider}
import com.sun.media.jmc.control.{AudioControl, VideoRenderControl}
import com.sun.media.jmc.event.{MediaStateEvent, MediaStateListener, VideoRendererEvent, VideoRendererListener}

class SquibMediaPane extends JComponent {
        var mediaProvider:MediaProvider = new MediaProvider()
        var videoRenderControl:VideoRenderControl = null
        var audioControl:AudioControl = null

        override def paintComponent(graphics:java.awt.Graphics) {
            if (mediaProvider != null && videoRenderControl != null) {
				videoRenderControl.paintVideoFrame(graphics, new Rectangle(0, 0,
                                    getWidth(), getHeight()));
                //graphics.drawString("Time: " + mediaProvider.getMediaTime(), 10 ,10)
            }            
        }

        def addMediaStateListener(cl:MediaStateListener) = mediaProvider.addMediaStateListener(cl)

        def getDuration() = mediaProvider.getDuration()

        def getMediaTime() = mediaProvider.getMediaTime()

        def isPlaying = mediaProvider.isPlaying

        def pause = mediaProvider.pause

        def play = mediaProvider.play

        def setMediaTime(v:Double) = mediaProvider.setMediaTime(v)

        def setMute(v:Boolean) = audioControl.setMute(v)

        def setVolume(v:Float) = audioControl.setVolume(v)

        def loadURI(uri:URI) {
            mediaProvider.setSource(uri)
            audioControl = mediaProvider.getControl(classOf[AudioControl])
            videoRenderControl = mediaProvider.getControl(classOf[VideoRenderControl])
            videoRenderControl.addVideoRendererListener(new VideoRendererListener() {
                override def videoFrameUpdated(videorendererevent:VideoRendererEvent) {
                    repaint();
                }
            });

            val videoSize = videoRenderControl.getFrameSize();
            setPreferredSize(new Dimension(videoSize.width / 2,	videoSize.height / 2));
        }
    }
